package naga.x.game.transaction.impl;

import java.util.ArrayList;
import java.util.List;

import naga.x.game.transaction.Transaction;
import naga.x.game.transaction.TransactionException;

public abstract class AbstractTransaction implements Transaction {

	public static final byte INIT = 0, COMMITTED = 1, ROLLEDBACK = 2;
	
	protected byte state = INIT;
	protected String cause;
	protected List<Transaction> items;
	
	public AbstractTransaction(String cause) {
		this.cause = cause;
		this.items = new ArrayList<Transaction>();
	}
	
	@Override
	public void commit() throws TransactionException {
		if (state == INIT) {
			for (int i = 0, size = items.size(); i < size; i++) {
				Transaction item = items.get(i);
				item.commit();
			}
			state = COMMITTED;
		}
	}

	@Override
	public void rollback() throws TransactionException {
		if (state == INIT) {
			for (int i = 0, size = items.size(); i < size; i++) {
				Transaction item = items.get(i);
				item.rollback();
			}
			state = ROLLEDBACK;
		}
	}

	public String getCause() {
		return cause;
	}
	
	public void add(Transaction item) {
		items.add(item);
	}

}
